#include "../common/etcd.hpp"
#include "../common/brpc.hpp"
#include <gflags/gflags.h>
#include "main.pb.h"
#include <brpc/server.h>
#include <butil/logging.h>
#include <thread>

DEFINE_bool(run_mode, false, "程序的运行模式，false-调试；true-发布");
DEFINE_string(log_file, "", "发布模式下，用于指定日志的输出文件");
DEFINE_int32(log_level, 0, "发布模式下，用于指定日志输出等级");

DEFINE_string(etcd_host, "127.0.0.1:2379", "服务注册中心地址");
DEFINE_string(base_service, "/service", "服务监控根目录");
DEFINE_string(instance_name, "/echo/instance", "当前实例名称");
DEFINE_string(access_host, "127.0.0.1:9090", "当前服务的外部地址");
DEFINE_int32(listen_port, 9090, "Rpc服务器监听端口");

// 1. 创建rpc服务子类继承pb(protobuf)中的EchoService服务类，并实现内部的业务接口逻辑；
class EchoServiceImpl : public example::EchoService
{
public:
    EchoServiceImpl(){}
    ~EchoServiceImpl(){}
    void Echo(google::protobuf::RpcController* controller,
        const ::example::EchoRequest* request,
        ::example::EchoResponse* response,
        ::google::protobuf::Closure* done) override
        {
            //使用ClosureGurd类管理done对象，防止出现未调用Run方法；
            brpc::ClosureGuard rpc_gurd(done);
            std::cout << "收到消息：" << request->message() << std::endl;
            //构建响应
            std::string str = request->message() + "---这是一个响应";
            response->set_message(str);

            // done->Run();
        }
private:
};

int main(int argc, char* argv[])
{
    google::ParseCommandLineFlags(&argc, &argv, true);
    ChatSystem::InitLogger(FLAGS_run_mode, FLAGS_log_file, FLAGS_log_level);

    //服务端改造思想：1. 构造Echo服务；2. 搭建Rpc服务器； 3. 运行Rpc服务； 4. 向etcd服务器注册服务
    //关闭brpc的默认日志输出
    logging::LoggingSettings settings;
    settings.logging_dest = logging::LoggingDestination::LOG_TO_NONE;
    logging::InitLogging(settings);
    // 2. 构建rpc服务器类，搭建服务器；
    brpc::Server server;
    // 3. 向rpc服务器类中添加rpc子服务对象---告诉服务器收到什么请求用哪个接口处理；
    EchoServiceImpl echo_service;
    int ret = server.AddService(&echo_service, brpc::ServiceOwnership::SERVER_DOESNT_OWN_SERVICE);
    if(ret == -1)
    {
        std::cout << "服务添加失败！" << std::endl;
        return -1;
    }
    // 4. 启动服务器
    brpc::ServerOptions options;
    options.idle_timeout_sec = -1;  //连接空闲超时时间---超时后连接关闭
    options.num_threads = 1;    //IO线程数量；
    ret = server.Start(FLAGS_listen_port, &options);
    if(ret == -1)
    {
        std::cout << "服务器启动失败！" << std::endl;
        return -1;
    }
    //5. 注册服务到etcd服务器中
    ChatSystem::Registry::ptr rclient = std::make_shared<ChatSystem::Registry>(FLAGS_etcd_host);
    //注册的是 /service/echo/instance ；发现的时候是 /service/echo 服务
    rclient->registry(FLAGS_base_service + FLAGS_instance_name, FLAGS_access_host);

    
    // 阻塞等待服务端运行 
    server.RunUntilAskedToQuit();   //休眠等待运行结束
    return 0;
}